<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style>
			*{
				margin:0;
				padding:0;
				box-sizing: border-box;
			}
			html,body{
				width:100%;
				height:100%;
				overflow:visible;
				/* border: 1px solid red; */
				/* background-color: #fff; */
			}
			#timeBox{
				width:100%;
				height:50px;
				line-height:50px;
				overflow: visible;
				font-size:16px;
				color:#000;
				padding-left:10px;
			}
			#timeBox span,#timeBox input{
				display:inline-block;
				font-size:16px;
			}
			
			#timeBox input{
				margin-left:4px;
				color:inherit;
				background-color:transparent!important;
				/* border:1px solid #fff; */
			}
			
			/* #timeBox i{
				display:inline-block;
				vertical-align:middle;
				font-size:30px;
				color:deepskyblue;
				margin-left:2%;
			} */
			#timeBox .refreshBtn{
				/* vertical-align:middle; */
				width:50px;
				height:28px;
				line-height:26px;
				/* padding-bottom:4px; */
				text-align: center;
				color:inherit;
				font-size:inherit;
				margin-left:2%;
				background-color: transparent;
				cursor: pointer;
			}
			
			.refreshBtn:hover{
				color:deepskyblue!important;
			}
			
			#content{
				width:100%;
				height:calc(100% - 50px);
				overflow: visible;
				/* padding-bottom: 5px; */
				/* border-top:1px dotted #111; */
			}
			#chartTip{
				width:100%;
				height:50px;
				line-height:50px;
				text-align:center;
				font-size: 16px;
				color:#eee;
			}
		</style>
		<script src="js/plugIn/jquery/jquery.min.js"></script>
	    <script src="js/plugIn/echart5.3.2/echarts.min.js"></script>
		<script src="js/plugIn/echart5.3.2/echarts-liquidfill.min.js"></script>
		<script src="config/echart/echartOption.js"></script>
	</head>
	<body id="box">
		<div id="timeBox">
			<span>起始日期:</span><input type="date" id="startTime" onchange="changeStartTime(this.value)"  value=""/>
			<span style="margin-left:2%;">截止日期:</span><input type="date" id="endTime" onchange="changeEndTime(this.value)" value=""/>
			<!-- <i class="fa fa-refresh" ></i> -->
			<button  onclick="searchEchart()" class="refreshBtn">查询</button>
		</div>
		<div id="content">
			<div id="chartTip">正在获取数据，请稍等...</div>
		</div>
		
		<script>
			//echart实例
			var myChart = null;
			//获取地址参数函数
			function getUrlParam(name){
				var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
				var r = window.location.search.substr(1).match(reg);  //匹配目标参数
				//unescape() 函数可对通过 escape() 编码的字符串进行解码。
				//通过找到形式为 %xx 和 %uxxxx 的字符序列（x 表示十六进制的数字），用 Unicode 字符 \u00xx 和 \uxxxx 替换这样的字符序列进行解码
				//ECMAScript v3 已从标准中删除了 unescape() 函数，并反对使用它，因此应该用 decodeURI() 和 decodeURIComponent() 取而代之。
				if (r!=null) {
					//console.log(decodeURI(r[2]));
					return decodeURI(r[2]); //返回参数值
				}else{
					return null; 
				} 
			};
			 
		    //获取颜色值并转换函数
		    function getColor(color){
				if(color && color.indexOf("*")==0){
					return "#"+color.substr(1,color.length-1);
				}else{
					return color;
				}
		    };
			//获取当前年月日或前几日并转换格式
			function getNowFormatDate(before=1) {  //1即今日
				//因为包含当天，所以要减1，不然就多一天
				var beforeTime=(before-1)*3600*24*1000;
				var today = new Date().getTime();
				var date = new Date(today-beforeTime);
				var seperator1 = "-";
				// var seperator2 = ":";
				var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
				var strDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
				//var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
				var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
			    return currentdate;
			};
			
			var baseURL = localStorage.getItem("baseURL");
			var lines= [];
			var lineColor=["#BD2020","#34c6ff","#ffc34d","#ff53Ad","#0099ff",
				"#ffff00","#55D55B","#9f3ed5","#009999","#FF7400"];
			//面板背景色	
			var bgColor = getColor(getUrlParam("bgColor"));
			//边框颜色
			var borderColor = getColor(getUrlParam("borderColor"));
			//边框粗细
			var borderWidth = Number(getUrlParam("borderWidth")) || 0;
			//边框圆角
			var borderRadius = Number(getUrlParam("borderRadius")) || 0;
			//头部文字色
			var headColor = getColor(getUrlParam("headColor"));
			
			document.getElementById("box").style.backgroundColor = bgColor;
			if(borderWidth){
			   document.getElementById("box").style.border=borderWidth+"px solid "+borderColor; 
			}
			if(borderRadius){
			   document.getElementById("box").style.borderRadius=borderRadius+"px";
			}
			document.getElementById("timeBox").style.color = headColor;
			document.getElementById("chartTip").style.color = headColor;
			document.getElementById("content").style.borderTop = "1px dotted "+headColor;
			
			//默认时段获取与设置
			var defaultDateType = Number(getUrlParam("dateRange")) || 1;
		    document.getElementById("startTime").value=getNowFormatDate(defaultDateType);
			document.getElementById("endTime").value=getNowFormatDate(1);
			var data_range=[getNowFormatDate(defaultDateType),getNowFormatDate(1)].join('~');
			var echartOption = new EchartOption();
			var option = echartOption.realTimeLine2();
			option.series=[];
			option.xAxis.data =[];
			option.legend.data = [];
			option.dataZoom= [{
					id: 'dataZoomX',
					type: 'slider',
					show: true,
					start: 95,
					end: 100,
					filterMode: 'filter',
					fillerColor: 'rgba(0,0,0,0.5)',
					backgroundColor: 'transparent',
					handleStyle: {
						color: '#409eff'
					},
					textStyle:{
						color:'#111'
					},
					bottom:15
				}
			
			];
			//XY轴轴线颜色
			option.yAxis.axisLine.lineStyle.color = getColor(getUrlParam("axisColorXY"));
			option.xAxis.axisLine.lineStyle.color = getColor(getUrlParam("axisColorXY"));
			//XY轴文字颜色和图例文字颜色
			option.yAxis.axisLabel.textStyle.color = getColor(getUrlParam("labelColorXY"));
			option.xAxis.axisLabel.textStyle.color = getColor(getUrlParam("labelColorXY"));
			option.legend.textStyle.color = getColor(getUrlParam("labelColorXY"));
			//横向分割线颜色
			option.yAxis.splitLine.lineStyle.color = [getColor(getUrlParam("splitColor"))];
			//底部滑动条滑块颜色
			option.dataZoom[0].fillerColor = getColor(getUrlParam("sliderColor"));
			
			
			function getData(){
				let data_range = this.data_range;
				let sensorCode = getUrlParam("sensorCode");
				//将多变量字符串转为数组
				let sensorArr = sensorCode.split(',');
				//取第一个变量字符串，取出设备id
				let sensorOne = sensorArr[0].split('@');
				let equipId = sensorOne[2];
				$.ajax({
				    type: "POST",
				    url: baseURL + "api/equip/graph",
				    data:{
						"id":equipId,
					    "sensor_code":sensorCode,
						"date_range":data_range,
						"token": localStorage.getItem("attoken")
					},
				    //cache: false,
				    async:false,  //同步如果数据量大，造成页面卡死，所以改为异步
				    beforeSend: function() {
				        //请求前要处理的事情
				    },
				    success: function (res) {//保存成功后，返回data，里面包含 stage_id  ,应为再次点击“保存”就是修改
				        if (res && res.result == 'success') {
				            let values = res.data.values.reverse();
							for (let key in res.data.field) {
								let line = {
									id: key,
									label: res.data.field[key]
								}
								lines.push(line);
							}
							for (let i = 0, len = values.length; i < len; i++) {
								option.xAxis.data.push(values[i].time.substr(5, 5) + "\n" +values[i].time.substr(11));
							}
							
							if (lines.length > 5) {
								for (let n = 0, len2 = lines.length; n < len2; n++) {
									option.legend.data.push(lines[n].label);
									option.series.push({
										name: lines[n].label,
										type: 'line',
										data: [],
										itemStyle: {
											normal: {
												color:lineColor[n]
											}
										},
										smooth: true
									});
								}
							} else {
								for (let n = 0, len2 = lines.length; n < len2; n++) {
									option.legend.data.push(lines[n].label);
									option.series.push({
										name: lines[n].label,
										type: 'line',
										data: [],
										markPoint: {
											data: [{
												type: 'max',
												name: '最大值'
											}, {
												type: 'min',
												name: '最小值'
											}]
										},
										markLine: {
											data: [{
												type: 'average',
												name: '平均值'
											}]
										},
										itemStyle: {
											normal: {
												color:lineColor[n]
											}
										},
										smooth: true
									});
								}
							}
							for (let n = 0, len3 = lines.length; n < len3; n++) {
								for (let i = 0, len4 = values.length; i < len4; i++) {
									option.series[n].data.push(values[i].data[lines[n].id])
								}
							}
				        } else {
							alert(res.msg);
						}
						return "success";
				    },
				    error: function (jqXHR) {
				        console.log("发生错误：" + jqXHR.status);
						return "error";
				    }
				});
			};
			
			function initEchart(){
				var chart = document.getElementById("content");
				myChart = echarts.init(chart);
				myChart.setOption(option);
				window.addEventListener("resize", () => {
					myChart.resize();
				})
			};
			
			function changeStartTime(val){
				if(!val){
					return;
				}
				this.data_range=val+'~'+document.getElementById("endTime").value;
			};
			
			function changeEndTime(val){
				if(!val){
					return; 
				}
				this.data_range=document.getElementById("startTime").value+'~'+val;
			};
			
			async function showEchart(){
				await getData();
				initEchart();
			};
			
			function searchEchart(){
				lines=[];
				option.series=[];
				option.xAxis.data =[];
				option.legend.data = [];
				if(myChart){
					myChart.dispose();
				}
				showEchart();
			};
			
			window.onload=function(){
				setTimeout(function(){
			       showEchart();
				   document.getElementById("chartTip").style.display = "none";
				},1000)
			}
				
		</script>
	</body>
</html>